/*
 * Created on 4/Abr/2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package org.cyborgas.xmltool;

import java.util.ArrayList;

import org.dom4j.Attribute;
import org.dom4j.Branch;
import org.dom4j.Comment;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.ProcessingInstruction;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

/**
 * @author rino
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class XmlTreeContentProvider implements ITreeContentProvider {

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
	 */
	public Object[] getChildren(Object item) {
		ArrayList list = new ArrayList();
		if (item instanceof Element) {
			Element element = (Element) item;
			for (int i = 0, size = element.attributeCount(); i < size; i++) {
				Attribute attribute = element.attribute(i);
				list.add(attribute);
			}
			list.addAll(getElementsList((Branch) item));
		}
		return list.toArray();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
	 */
	public Object getParent(Object item) {
		return ((Node) item).getParent();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
	 */
	public boolean hasChildren(Object item) {
		boolean result;
		if (item instanceof Element) {
			result = getChildren(item).length > 0;
		} else {
			result = false;
		}

		return result;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
	 */
	public Object[] getElements(Object item) {
		return getElementsList((Branch) item).toArray();
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.IContentProvider#dispose()
	 */
	public void dispose() {
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
	 */
	public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
	}

	private ArrayList getElementsList(Branch branch) {
		ArrayList list = new ArrayList();
		for (int i = 0, size = branch.nodeCount(); i < size; i++) {
			Node node = branch.node(i);
//			System.out.println(node.getClass() + "; " + node);
			if (node instanceof Element || node instanceof Comment || node instanceof ProcessingInstruction) {
				list.add(node);
			}
		}
		return list;
	}

}
